import java.io.*;
import java.util.*;

public class Request {
    //输入流
    private InputStream is;

    //请求方式
    private String method;

    //请求资源
    private String url;

    //session
    private Session session;
    public Session getSession() {
        return session;
    }
    //请求参数
    private Map<String, String> parameterMap = new HashMap<>();

    //设置的请求属性
    private Map<String, String> attributeMap = new HashMap<>();

    public Request(InputStream is,Session session) throws IOException {
        this.session=session;
        this.is = is;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
        String request = bufferedReader.readLine();//GET /xxx/yyy HTTP/1.1
        if (request == null)
            request = new String("GET /asdasdszXcxzcasdfa HTTP/1.1");
        System.out.println("request " + request);
        String[] split = request.split(" ");
        System.out.println("split " + split);
        method = split[0];
        url = split[1];//  得到url    /xxx/yyy/zzz?a=1&b=2


        //获得参数   /xxx/yyy/zzz?a=1&b=2
        //根据不同请求方式封装请求参数和请求资源
        String param = "";
        if (method.equalsIgnoreCase("post")) {//获得post的参数
            char cp[]=new char[2048];
            bufferedReader.read(cp);
            System.out.println(cp);
            String s1 = new String(cp);
            String[] split3 = s1.split("\\r\\n");
            param = split3[split3.length - 1];
            System.out.println("post param::"+param);
        } else if (method.equalsIgnoreCase("get")) {
            if (url.contains("?")) {
                String[] arr = url.split("\\?");//转义
                url = arr[0];//   /xxx/yyy/zzz
                param = arr[1];// a=1&b=2
            }
        }
        //解析请求参数，并封装到集合中    a=1&b=2
        if (param != "") {
            String[] split1 = param.split("&");
            for (String s : split1) {
                String[] split2 = s.split("=");
                if(split2.length==1)
                    parameterMap.put(split2[0], "null");
                else
                    parameterMap.put(split2[0], split2[1]);
            }
        }
    }

    public String getMethod() {
        return method;
    }

    public String getUrl() {
        return url;
    }

    public String getParameter(String name) {
        return parameterMap.get(name);
    }

    public String getAttribute(String name){
        return attributeMap.get(name);
    }
    public String setAttribute(String name,String value){
        return attributeMap.put(name,value);
    }
}
